const bcrypt = require("bcrypt");

const UserModel = require("../modules/user");

const jwt = require("jsonwebtoken");

const SECRET_KEY = require("../config/jwt");

exports.register = async function (req, res) {
    const { userName, role, password } = req.body;
    if (!userName || !role || !password) {
        res.send({
            code: 401,
            msg: "用户名、用户类型、密码为必填",
        });
    }
    const user = new UserModel({
        userName: userName,
        role,
        password: await bcrypt.hash(password, 10),
    });
    const userInfo = await user.register();
    res.send(userInfo);
};

exports.login = async function (req, res) {
    const { userName, password } = req.body;
    console.log(userName, password, "login");
    if (!userName || !password) {
        res.send({
            code: 200,
            msg: "用户名密码不能为空",
        });
    }

    const [users, info] = await UserModel.login(userName);
    if (users.length <= 0) {
        res.send({
            code: 401,
            msg: "用户名不存在",
        });
        return;
    }

    const user = users[0];
    if (!bcrypt.compareSync(password, user.password)) {
        res.send({
            code: 401,
            msg: "密码错误",
        });
        return;
    }
    // token 生成注册role 和 userId
    const token = jwt.sign({ id: user.id,role:user.role }, SECRET_KEY, { expiresIn: "24h" });
    res.send({
        code: 200,
        msg: "登录成功",
        data: {
            token: token,
            role: user.role,
            userName: user.userName,
        },
    });
};

exports.getUserInfo = async (req, res) => {
    const userId = req.userId;
    const [users, rowInfo] = await UserModel.getUserInfo(userId);
    if (users.length <= 0) {
        res.status(404).send({
            code: 200,
            msg: "用户不存在",
        });
    }
    const { userName, role } = users[0];
    res.send({
        code: 200,
        msg: "成功获取用户信息",
        data: {
            userName,
            role,
        },
    });
};

